package main

import (
	"alertmanager-webhook/config"
	"alertmanager-webhook/model"
	"alertmanager-webhook/notifier/dingtalk"
	"alertmanager-webhook/notifier/wechat"
	"flag"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

var (
	h bool
)

func init() {
	flag.BoolVar(&h, "h", false, "help")
}

func main() {
	flag.Parse()
	if h {
		flag.Usage()
		return
	}
	err := config.LoadCongFromToml("config.toml")
	if err != nil {
		log.Fatal(err)
	}
	log.Println(config.C.String())
	r := gin.Default()
	r.POST("/webhook", func(c *gin.Context) {
		var notification model.Notification
		err := c.BindJSON(&notification)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}
		if config.C.Channel.Dingtalk.Enabled {
			err := dingtalk.SendDingTalk(notification, config.C.Channel.Dingtalk.Webhook)
			if err != nil {
				c.JSON(http.StatusBadRequest, gin.H{
					"error": err.Error(),
				})
				return
			}
		} else {
			err := wechat.SendWechat(notification, config.C.Channel.Wechat.Webhook)
			if err != nil {
				c.JSON(http.StatusBadRequest, gin.H{
					"error": err.Error(),
				})
				return
			}
		}
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		}
		c.JSON(http.StatusOK, gin.H{
			"message": "successful receive alert notification message",
		})
	})
	log.Panic(r.Run())
}
